package com.xinbochuang.machine.framework.security.custom;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 身份证号登录过滤器
 *
 * @author 黄晓鹏
 * @date 2020-09-14 11:09
 */
public class IdCardAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "idCard";

    private String IdCardParameter = SPRING_SECURITY_FORM_USERNAME_KEY;

    private boolean getOnly = true;

    public IdCardAuthenticationFilter() {
        //路径
        super(new AntPathRequestMatcher("/api/login", "GET"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        if (getOnly && !request.getMethod().equals("GET")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }

        String username = obtainUsername(request);

        if (username == null) {
            username = "";
        }

        username = username.trim();

        IdCardAuthenticationToken authRequest = new IdCardAuthenticationToken(username);

        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

    protected String obtainUsername(HttpServletRequest request) {
        return request.getParameter(IdCardParameter);
    }

    protected void setDetails(HttpServletRequest request,
                              IdCardAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    public void setUsernameParameter(String usernameParameter) {
        Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
        this.IdCardParameter = usernameParameter;
    }


    public void setGetOnly(boolean getOnly) {
        this.getOnly = getOnly;
    }

    public final String getUsernameParameter() {
        return IdCardParameter;
    }
}
